/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.controller.ui;

import lombok.extern.slf4j.Slf4j;
import me.zhengjie.annotation.Log;
import me.zhengjie.domain.FileService;
import me.zhengjie.dto.Resp;
import me.zhengjie.dto.Response;
import me.zhengjie.dto.sqlServer.Storage;
import me.zhengjie.service.StorageService;
import me.zhengjie.service.dto.StorageQueryCriteria;
import me.zhengjie.wcs.WmsToWcs;
import org.apache.catalina.LifecycleState;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import me.zhengjie.utils.PageResult;
import me.zhengjie.service.dto.StorageDto;
import org.springframework.web.multipart.MultipartFile;

/**
* @website https://eladmin.vip
* @author zhangYY
* @date 2024-01-12
**/
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "储位管理管理")
@RequestMapping("/api/storage")
public class StorageController {

    private final StorageService storageService;
    private final FileService fileService;

    private final WmsToWcs wmsToWcs;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('storage:list')")
    public void exportStorage(HttpServletResponse response, StorageQueryCriteria criteria) throws IOException {
        storageService.download(storageService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询储位管理")
    @ApiOperation("查询储位管理")
    @PreAuthorize("@el.check('storage:list')")
    public ResponseEntity<PageResult<StorageDto>> queryStorage(StorageQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(storageService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增储位管理")
    @ApiOperation("新增储位管理")
    @PreAuthorize("@el.check('storage:add')")
    public ResponseEntity<Object> createStorage(@Validated @RequestBody Storage resources){
        storageService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改储位管理")
    @ApiOperation("修改储位管理")
    @PreAuthorize("@el.check('storage:edit')")
    public ResponseEntity<Object> updateStorage(@Validated @RequestBody Storage resources){
        storageService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除储位管理")
    @ApiOperation("删除储位管理")
    @PreAuthorize("@el.check('storage:del')")
    public ResponseEntity<Object> deleteStorage(@RequestBody Integer[] ids) {
        storageService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @GetMapping("/uploadStorage")
    @Log("上传储位信息")
    @ApiOperation("上传储位信息")
    public Resp uploadStorage(){
        try {
            List<Storage> storageList = storageService.findAllOpenStorages();
            log.info(storageList.toString());
            wmsToWcs.sendStorage(storageList);
            return Resp.builder()
                    .status(200)
                    .msg("上传储位信息成功")
                    .build();
        } catch (Exception e) {
            log.error("上传储位信息失败，错误原因：{}", e.toString());
            return Resp.builder()
                    .status(500)
                    .msg("上传储位信息失败")
                    .build();
        }
    }

    @PostMapping("/inputStorage")
    @Log("储位数据维护")
    @ApiOperation("储位数据维护")
    public Resp uploadStorageExcel(@RequestParam("file")MultipartFile file){
        try {
            fileService.saveStorageExcelData(file);
            return Resp.builder()
                    .status(200)
                    .msg("同步成功")
                    .build();
        } catch (Exception e) {
            log.error("文件同步失败，失败原因：{}",e.toString());
            return Resp.builder()
                    .status(500)
                    .msg("文件同步失败")
                    .build();
        }
    }

    @GetMapping("/changeStorageStatus/{storageId}/{storageStatus}")
    @Log("更改储位状态")
    @ApiOperation("更改储位状态")
    public Resp changeStorageStatus(@PathVariable("storageId")Integer storageId, @PathVariable("storageStatus") Integer storageStatus){
        int result = storageService.changeStorageStatusById(storageStatus,storageId);
        if(result == 1){
            return Resp.builder()
                    .status(200)
                    .msg("储位状态更新成功")
                    .build();
        }else {
            return Resp.builder()
                    .status(200)
                    .msg("储位状态更新失败")
                    .build();
        }
    }
}